package team.nmsg.photo.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import team.nmsg.ge.system.bean.PageObject;
import team.nmsg.ge.system.controller.BaseController;
import team.nmsg.photo.bean.PhotoBean;
import team.nmsg.photo.bean.ProjectBean;
import team.nmsg.photo.service.IPhotoService;
import team.nmsg.photo.util.JSApiSignature;
import team.nmsg.photo.util.WXAccessToken;
import team.nmsg.photo.util.WXJSApiTicket;
import team.nmsg.photo.util.WxUtil;

@CrossOrigin
@RestController
@RequestMapping("/guest")
public class GuestController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(GuestController.class);
	
	@Autowired
	IPhotoService photoService ;
	
	
	@RequestMapping("/getImgs")    
    public String getImgs(HttpServletRequest request,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		JSONArray arr = new JSONArray();
		for(  int i=1; i<12 ;i++ ) {
			PhotoBean tmp = new PhotoBean();
			tmp.setPid(i + 0L);
			tmp.setImgPath("/resources/photo/"+i+".jpg");
			tmp.setImg2Path("/resources/photo/"+i+".jpg");
			tmp.setImgTitle("" );
			tmp.setImgDesc(""  );
			tmp.setCreateTime(System.currentTimeMillis());
			
			BufferedImage bufferedImage = null ;
			try {
				bufferedImage = ImageIO.read(new FileInputStream( "resources/photo/"+i+".jpg" )  );
				int width = bufferedImage.getWidth();
				int height = bufferedImage.getHeight();
				
				tmp.setImgWidth(width);
				tmp.setImgHeight(height);
				tmp.setImgWidth2(width/2);
				tmp.setImgHeight2(height/2);
				
			} catch (IOException e) {
				e.printStackTrace();
			}



			arr.add(tmp);
		}
		
		obj.put("result", true);
		obj.put("imgs", arr);
		
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		writeJson(obj, response);
		return null;
    }

	
	
	@RequestMapping("/getImgsByPro")    
    public String getImgsByPro(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		String pageSize = req.getParameter("pageSize");
		String currentPage = req.getParameter("currentPage");
		String projectIdStr = req.getParameter("projectId");
		
		int startIndex = 0;
		startIndex = Integer.parseInt(pageSize) * (Integer.parseInt(currentPage) - 1);
		
		PhotoBean criteria = new PhotoBean();
		criteria.setIsQueryProject(true);
		criteria.setProjectId(Long.parseLong(projectIdStr));
		PageObject<PhotoBean> page = photoService.getPhotos( criteria, Integer.parseInt(pageSize), startIndex );
		
		JSONArray arr = new JSONArray();

		Object extInfo = page.getExtInfo();
		if( extInfo instanceof ProjectBean   ) {
			ProjectBean pro = (ProjectBean) extInfo;
			obj.put("proTitle",  pro.getProTitle() );
			
			for( PhotoBean photo : page.getCurrentEntitys()  ) {
				photo.setTmpPro(pro);
				arr.add( photo.toJson() );
			}
		}
		obj.put("result", true);
		obj.put("imgs", arr);
		obj.put("total", page.getSumCount());
		
		writeJson(obj, response);
		return null;
    }
	
	@RequestMapping("/getPros")    
    public String getPros(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		String pageSize = req.getParameter("pageSize");
		String current = req.getParameter("current");
		String isGetActive = req.getParameter("isGetActive");
		int startIndex = Integer.parseInt(current) ;
		
		boolean isGet =Boolean.parseBoolean(isGetActive);// 是否获取 正在进行的活动
		
		ProjectBean criteria = new ProjectBean();
		
		PageObject<ProjectBean> page = photoService.getPros( criteria , Integer.parseInt(pageSize), startIndex  , isGet);
		
		JSONArray proArr = new JSONArray();
		List<ProjectBean> currentEntitys = page.getCurrentEntitys();
		for(  ProjectBean bean :  currentEntitys ) {
			proArr.add( bean.toJson() );
		}
		
		Object extInfo = page.getExtInfo();
		if(  extInfo instanceof List  ) {
			JSONArray activeArray = new JSONArray();
			List<ProjectBean> activePros =  (List<ProjectBean>) extInfo;
			for(  ProjectBean bean :  activePros ) {
				activeArray.add( bean.toJson() );
			}
			obj.put("activePro", activeArray);
		}
		
		obj.put("pro", proArr);
		obj.put("total", page.getSumCount() );
		int size = startIndex + currentEntitys.size();
		obj.put("current",  size  );
		obj.put("result", true);
		writeJson(obj, response);
		return null;
	}
	
	@RequestMapping("/getImgsByPro2")    
    public String getImgsByPro2(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		String current = req.getParameter("current");
		String pageSize = req.getParameter("pageSize");
		String projectIdStr = req.getParameter("projectId");
		
		int startIndex = Integer.parseInt(current) ;
		
		PhotoBean criteria = new PhotoBean();
		criteria.setIsQueryProject(true);
		criteria.setProjectId(Long.parseLong(projectIdStr));
		PageObject<PhotoBean> page = photoService.getPhotos( criteria, Integer.parseInt(pageSize), startIndex );
		
		JSONArray arr = new JSONArray();

		Object extInfo = page.getExtInfo();
		if( extInfo instanceof ProjectBean   ) {
			ProjectBean pro = (ProjectBean) extInfo;
			JSONObject json = pro.toJson();
			obj.put("proInfo", json );
			
			for( PhotoBean photo : page.getCurrentEntitys()  ) {
				photo.setTmpPro(pro);
				arr.add( photo.toJson() );
			}
		}
		obj.put("result", true);
		obj.put("imgs", arr);
		obj.put("total", page.getSumCount());
		int size = startIndex + page.getCurrentEntitys().size();
		obj.put("current",  size  );
		
		writeJson(obj, response);
		return null;
    }
	
	
	@RequestMapping("/getProsByCriteria")    
	public String getProsByCriteria(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		String pageSize = req.getParameter("pageSize");
		String current = req.getParameter("current");
		int startIndex = Integer.parseInt(current) ;
		
		
		String proTitle = req.getParameter("proTitle");
		String classType = req.getParameter("classType");
		String status = req.getParameter("status");
		
		ProjectBean criteria = new ProjectBean();
		criteria.setProTitle(proTitle);
		criteria.setClasstype(classType);
		criteria.setStatus( Integer.parseInt(status) );
		
		PageObject<ProjectBean> page = photoService.getProsByCriteria( criteria , Integer.parseInt(pageSize), startIndex );
		
		JSONArray proArr = new JSONArray();
		List<ProjectBean> currentEntitys = page.getCurrentEntitys();
		for(  ProjectBean bean :  currentEntitys ) {
			proArr.add( bean.toJson() );
		}
		
		obj.put("pro", proArr);
		obj.put("total", page.getSumCount() );
		int size = startIndex + currentEntitys.size();
		obj.put("current",  size  );
		obj.put("result", true);
		writeJson(obj, response);
		
		return null;
	}
	
	
	@RequestMapping("/getMainPage")    
	public String getMainPage(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		obj = photoService.getMainPage();
		
		obj.put("result", true);
		
		writeJson(obj, response);
		return null;
	}
	
	@RequestMapping("/addAccessCount")    
    public String addAccessCount(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		try {
			String parameter = req.getParameter("pid");
			String lock = "PROID_" + parameter;
			synchronized ( lock.intern() ) {
				photoService.addAccessCount(Long.parseLong(parameter) );
			}
		} catch (Exception e) {
			log.error( " "  , e );
		}
		
		obj.put("result", true );
		
		writeJson(obj, response);
		return null;
	}
	
	@RequestMapping("/test2")    
    public String test2(HttpServletRequest req,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		String parameter = req.getParameter("pid");
		
		
		obj.put("parameter", parameter );
		
		obj.put("result", true );
		
		writeJson(obj, response);
		return null;
	}
	
//	@RequestMapping("/test1")    
//    public String test1(HttpServletRequest request,HttpServletResponse response ) {    
//		JSONObject obj = new JSONObject();
//		
//		WXAccessToken access_token = WxUtil.getAccess_token();
//		WXJSApiTicket jsapi_ticket = WxUtil.getJsapi_ticket();
//		
//		obj.put("access_token", access_token);
//		obj.put("jsapi_ticket", jsapi_ticket);
//		
//		writeJson(obj, response);
//		return null;
//	}
	
	@RequestMapping("/doShareSignForUrl")    
    public String doShareSignForUrl(HttpServletRequest req ,HttpServletResponse response ) {    
		JSONObject obj = new JSONObject();
		
		
		String shareUrl = req.getParameter( "shareUrl" );
		
		JSONObject sign = WxUtil.signForShareUrl(shareUrl);
		
		obj.put("result", true);
		obj.put("sign", sign);
		
		JSONObject shareInfo = new JSONObject();
		shareInfo.put("title", "this is a share titile");
		shareInfo.put("desc", "Share desc ................. ");
		obj.put("shareInfo", shareInfo);
		
		writeJson(obj, response);
		return null;
	}
	
}
